
import { _decorator, Component, instantiate, Node,Prefab,sp, tween, Vec2,Vec3 } from 'cc';
import { LINEUP_TYPE,CHARACTOR_STATUS } from './Enum';
import { AppLauncher } from './AppLauncher';
const { ccclass, property } = _decorator;

// 角色数据
var CharacterDataListLeft = [
    {skeletonIndex: 0, x: -145, y: -150, speed: 6, atk: 50, def: 30, long: false, blood: 100},
    {skeletonIndex: 1, x: -350, y: -145, speed: 8, atk: 55, def: 25, long: false, blood: 100},
    {skeletonIndex: 2, x: -220, y: -220, speed: 10, atk: 60, def: 20, long: false, blood: 100},
    {skeletonIndex: 3, x: -410, y: -255, speed: 7, atk: 50, def: 30, long: false, blood: 100},
    {skeletonIndex: 4, x: -290, y: -330, speed: 12, atk: 40, def: 30, long: false, blood: 100},
]

var CharacterDataListRight = [
    {skeletonIndex: 5, x: -145, y: -150, speed: 11, atk: 50, def: 30, long: false, blood: 100},
    {skeletonIndex: 6, x: -350, y: -145, speed: 9, atk: 55, def: 25, long: false, blood: 100},
    {skeletonIndex: 7, x: -220, y: -220, speed: 5, atk: 65, def: 30, long: false, blood: 100},
    {skeletonIndex: 8, x: -410, y: -255, speed: 6, atk: 40, def: 20, long: false, blood: 100},
    {skeletonIndex: 9, x: -290, y: -330, speed: 7, atk: 45, def: 30, long: false, blood: 100},
]

@ccclass('UIBattleFieldCtrl')
export class UIBattleFieldCtrl extends Component {

    private order : any[] = null;
    
    private leftCharacters : any[] = null;
    private rightCharacters : any[] = null;

    private targetIndx : number = null;

    private orderIndx = null;

    private __InitData() {
        this.order = [];
        for(var i=0;i<5;++i)
        {
            this.order[i] = {"speed":CharacterDataListLeft[i].speed,"atk":CharacterDataListLeft[i].atk,"def":CharacterDataListLeft[i].def,
            "status":CHARACTOR_STATUS.CHARACTOR_STATUS_WAIT ,"id":i ,"lpType":LINEUP_TYPE.LINEUP_TYPE_LEFT,"blood":CharacterDataListLeft[i].blood,"long":CharacterDataListLeft[i].long};
            this.order[i+5] = {"speed":CharacterDataListRight[i].speed,"atk":CharacterDataListRight[i].atk,"def":CharacterDataListRight[i].def,
            "status":CHARACTOR_STATUS.CHARACTOR_STATUS_WAIT ,"id":i ,"lpType":LINEUP_TYPE.LINEUP_TYPE_RIGHT,"blood":CharacterDataListRight[i].blood,"long":CharacterDataListRight[i].long};
        }
        //sort
        function orderSort(a:any,b:any){
            return b.speed - a.speed;
        };
        this.order.sort(orderSort);
        this.orderIndx = 0;

        //init character data
        this.leftCharacters = []
        this.rightCharacters = []
        for (var i = 0; i < 5; i++) {
            //初始化左边阵容动画
            var data = CharacterDataListLeft[i]
            this.leftCharacters[i] = instantiate(AppLauncher.Instance.Charactor)
            this.leftCharacters[i].setPosition(data.x, data.y)
            AppLauncher.Instance.Canvas.addChild(this.leftCharacters[i])

            this.leftCharacters[i].getComponent(sp.Skeleton).skeletonData = AppLauncher.Instance.SkeletonDatas[data.skeletonIndex];
            this.leftCharacters[i].getComponent(sp.Skeleton).animation = "Idle"

            //初始化右边阵容动画
            data = CharacterDataListRight[i]
            this.rightCharacters[i] = instantiate(AppLauncher.Instance.Charactor)
            this.rightCharacters[i].setPosition(-data.x, data.y)
            AppLauncher.Instance.Canvas.addChild(this.rightCharacters[i])
            var originScale = this.rightCharacters[i].scale
            this.rightCharacters[i].setScale(new Vec3(-originScale.x, originScale.y, originScale.z))

            this.rightCharacters[i].getComponent(sp.Skeleton).skeletonData = AppLauncher.Instance.SkeletonDatas[data.skeletonIndex];
            this.rightCharacters[i].getComponent(sp.Skeleton).animation = "Idle"
            //this.rightCharacters[i].getComponent("CharacterController").setBloodSpriteFrame(SpriteFrame.createWithImage(AppLauncher.Instance.ImageAssetHealthPercent));
        }
    }

    start () {
        this.__InitData();
        //battle
        this.__nextBattle();
    }

    __nextBattle(){ 
        if(this.orderIndx > 9){
            this.orderIndx = 0;
        }
        var self = this.order[this.orderIndx]
        if(self.status == CHARACTOR_STATUS.CHARACTOR_STATUS_WAIT){
            this.__setAnimation(self,CHARACTOR_STATUS.CHARACTOR_STATUS_MOVE);
        }
        else{
            ++this.orderIndx;
            this.__nextBattle();
        }
    }

    __setAnimation(self : any,status : CHARACTOR_STATUS){
        self.status = status
        //selfAnimation
        var selfAnimation = null;
        selfAnimation = this.leftCharacters[self.id];
        var targetLpType:LINEUP_TYPE = LINEUP_TYPE.LINEUP_TYPE_RIGHT;
        if(self.lpType == LINEUP_TYPE.LINEUP_TYPE_RIGHT)
        {
            targetLpType = LINEUP_TYPE.LINEUP_TYPE_LEFT;
            selfAnimation = this.rightCharacters[self.id];
        }

        if(status == CHARACTOR_STATUS.CHARACTOR_STATUS_MOVE)
        {
            //find target
            var target = null;
            for(var i=0;i<this.order.length;++i)
            {
                if(this.order[i].lpType == targetLpType && this.order[i].blood > 0)
                {
                    target = this.order[i];
                    this.targetIndx = i;
                    break;
                }
            }
            if(!target){
                console.log("游戏结束");
                var UIBattleEnd = instantiate(AppLauncher.Instance.UIBattleEnd);
                AppLauncher.Instance.Canvas.addChild(UIBattleEnd);
                //battle end
                return;
            }

            //long
            if(self.long)
            {
                //ATK
                this.__setAnimation(self,CHARACTOR_STATUS.CHARACTOR_STATUS_ATK);
                return ;
            }

            //MOVE
            var targetPos = new Vec2(0,0);

            if(targetLpType == LINEUP_TYPE.LINEUP_TYPE_LEFT)
            {
                targetPos.x = CharacterDataListRight[target.id].x + 80;
                targetPos.y = CharacterDataListRight[target.id].y;
            }
            else
            {
                targetPos.x = -(CharacterDataListRight[target.id].x + 80);
                targetPos.y = CharacterDataListRight[target.id].y;
            }
            //不懂
            selfAnimation.setSiblingIndex(selfAnimation.parent.children.length-1)

            var callback = function() {
                //进入到攻击状态
                this.__setAnimation(self,CHARACTOR_STATUS.CHARACTOR_STATUS_ATK)
            }.bind(this)
            tween(selfAnimation).to(0.5, {position: new Vec3(targetPos.x, targetPos.y,0)}).call(callback).start();
        }
        else if(status == CHARACTOR_STATUS.CHARACTOR_STATUS_ATK)
        {
            selfAnimation.getComponent(sp.Skeleton).animation = "Attack";
            selfAnimation.getComponent(sp.Skeleton).setCompleteListener((trackEntry : sp.spine.TrackEntry)=>{
                //攻击表演完毕之后会调用，执行扣血
                //find target
                var target = this.order[this.targetIndx];
                target.blood = target.blood - Math.abs(self.atk - target.def);
                if(target.blood < 0)
                {
                    target.blood = 0;
                } 
                var targetNode = null;
                if(target.lpType == LINEUP_TYPE.LINEUP_TYPE_LEFT)
                {
                    targetNode = this.leftCharacters[target.id];
                }
                else
                {
                    targetNode = this.rightCharacters[target.id];
                }

                //origin pos
                var originPos = new Vec2(0,0);
                if(self.lpType == LINEUP_TYPE.LINEUP_TYPE_LEFT)
                {
                    originPos.x = CharacterDataListLeft[self.id].x;
                    originPos.y = CharacterDataListLeft[self.id].y;                    
                }
                else
                {
                    originPos.x = -CharacterDataListLeft[self.id].x;
                    originPos.y = CharacterDataListLeft[self.id].y;    
                }
                
                //掉血
                targetNode.getComponent("CharactorCtrl").setBlood(target.blood/100)
                if (target.blood <= 0) {
                    //角色死亡
                    this.__setAnimation(target,CHARACTOR_STATUS.CHARACTOR_STATUS_DLE);
                }
                if(self.long)
                {
                    //进入到待机状态
                    this.__setAnimation(self,CHARACTOR_STATUS.CHARACTOR_STATUS_WAIT)
                    return ;
                }
                //退回到原来位置
                selfAnimation.getComponent(sp.Skeleton).setCompleteListener((trackEntry: sp.spine.TrackEntry) => {
                })
                selfAnimation.getComponent(sp.Skeleton).animation = "Run"

                var callback = function() {
                    //进入到待机状态
                    this.__setAnimation(self,CHARACTOR_STATUS.CHARACTOR_STATUS_WAIT)
                }.bind(this)
                tween(selfAnimation).to(0.5, {position: new Vec3(originPos.x, originPos.y, 0)}).call(callback).start();
            });
        }
        else if(status == CHARACTOR_STATUS.CHARACTOR_STATUS_DLE)
        {
            console.log("死亡");
            selfAnimation.getComponent("CharactorCtrl").setBloodVisible(false)

            selfAnimation.getComponent(sp.Skeleton).setAnimation(0,"Die",false)
            selfAnimation.getComponent(sp.Skeleton).setCompleteListener((trackEntry: sp.spine.TrackEntry) => {
                selfAnimation.active = false
                selfAnimation = null;
            })
        }
        else if (status == CHARACTOR_STATUS.CHARACTOR_STATUS_WAIT) {
            //回到原始状态
            selfAnimation.getComponent(sp.Skeleton).animation = "Idle"
            this.orderIndx = this.orderIndx + 1
            this.__nextBattle()
        }
    }

}
